package com.weibotwo.web.controller;


import com.weibotwo.common.util.PageResult;
import com.weibotwo.pojo.Message;
import com.weibotwo.pojo.User;
import com.weibotwo.service.FriendService;
import com.weibotwo.service.UserService;
import com.weibotwo.service.WeiBoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @ClassName FriendController
 * @Author 天火
 * @Date 2019-03-12
 * @Version 1.0
 */
@Controller
public class FriendController {

    private ModelAndView modelAndView = new ModelAndView() ;

    @Autowired
    private UserService userService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private WeiBoService weiBoService;

    private  List<User> userTuiJian;

    /**
     * 好友主页面
     * @param session
     * @return
     */
    @RequestMapping("/friend")
    public ModelAndView friendIndex(HttpSession session,@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        modelAndView.clear();
        modelAndView.setViewName("friend/friend");
        User user = (User)session.getAttribute("loginUser");
        try {
            if(user==null){
                modelAndView.setViewName("login");
                return modelAndView;
            }
            PageResult pageResult = friendService.findFriendWeibo(user.getId(),pageNum);
            userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("pageNum", pageNum);
            modelAndView.addObject("totalPage",pageResult.getPageTotals());
            modelAndView.addObject("weiboList", pageResult.getRows() );


        }catch (Exception e){
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 用户关注好友
     */
    @RequestMapping("/attenIndex")
    public ModelAndView attenFriend(HttpSession session,String msg, @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){

        try{
            User user = (User)session.getAttribute("loginUser");
            if(user == null){
                modelAndView.setViewName("login");
                return modelAndView;
            }
            modelAndView.clear();
            modelAndView.setViewName("friend/attenFriend");
            PageResult pageResult = friendService.findAttentionUserListByUserId(user.getId(),pageNum);
            user.setAttention(pageResult.getTotals());
            userService.updateUser(user);
            session.removeAttribute("loginUser");
            session.setAttribute("loginUser",user);
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("pageNum",pageNum);
            modelAndView.addObject("attUsers", pageResult.getRows());
            modelAndView.addObject("totalPage", pageResult.getPageTotals());
            modelAndView.addObject("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    @RequestMapping("toAttentionOrUnsubscribe")
    public ModelAndView friendToBlackOrQXGZ(HttpSession session,long bUserId,String operation){
        modelAndView.clear();
        modelAndView.setViewName("friend/attenFriend");
        User aUser = (User)session.getAttribute("loginUser");
        try {
            User bUser = userService.findUserByID(bUserId);
            if(aUser == null){
                modelAndView.addObject("msg","请登录");
                return modelAndView;
            }
            friendService.operationUser(operation,aUser,bUser);
            if("unsubscribe".equals(operation)){
                modelAndView.addObject("msg", "已取消关注该用户！");
            }else if("LH".equals(operation)){
                modelAndView.addObject("msg", "已成功拉黑该用户！");
            }
            else if("attention".equals(operation)){
                modelAndView.addObject("msg", "已成功关注该用户！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 用户关注好友
     */
    @RequestMapping("/fansIndex")
    public ModelAndView fansFriend(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,HttpSession session,String msg){
        modelAndView.clear();
        modelAndView.setViewName("friend/fans");
        User user = (User)session.getAttribute("loginUser");
        if(pageNum == null) {
            pageNum = 1;
        }

        if(user==null){
            modelAndView.setViewName("login");
            return modelAndView;
        }

        try{

            PageResult result= friendService.findFansByUserId(user.getId(),pageNum);
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("fans", result.getRows());
            modelAndView.addObject("totalPage", result.getPageTotals());
            modelAndView.addObject("pageNum",pageNum);
            modelAndView.addObject("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    @RequestMapping("/blackIndex")
    public ModelAndView blankIndex(Integer p,HttpSession session,String msg){
        modelAndView.clear();
        modelAndView.setViewName("friend/black");
        User user = (User)session.getAttribute("loginUser");
        if(user==null){
            modelAndView.setViewName("login");
            return modelAndView;
        }
        try{

            PageResult result= friendService.findBlacksUserByUserId(user.getId(),p);
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("fans", result.getRows());
            modelAndView.addObject("totalPage", result.getPageTotals());
            modelAndView.addObject("page",p);
            modelAndView.addObject("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    @RequestMapping("/toBlack")
    public ModelAndView friendToBlackOrQXGZ(HttpSession session,long bId){
        modelAndView.clear();
        modelAndView.setViewName("redirect:attenIndex");
        User auser = (User)session.getAttribute("loginUser");
        try {
            User bUser = userService.findUserByID(bId);
            friendService.operationUser("LH", auser, bUser);
            String msg ="已成功拉黑该用户";
            msg = new String(msg.getBytes("ISO_8859_1"),"UTF-8");
            modelAndView.addObject("msg", msg);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("sendMessage")
    public ModelAndView sendMessage(HttpSession session,long userBId,String inputBox){
        modelAndView.clear();
        modelAndView.setViewName("friend/message");
        User user = (User)session.getAttribute("loginUser");
        try {
            //处理发布私信
            Message message = new Message();
            message.setMessage(inputBox);
            message.setUserAId(user.getId());
            message.setUserBId(userBId);

            friendService.sendMessage(message);
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            //查找用户有私信的记录
            Map<String, Object> map = friendService.findMessageNOReadById(user.getId(), userBId);
            @SuppressWarnings("unchecked")
            List<Message> Messagelist = (List<Message>) map.get("list");
            User bUser = (User) map.get("bUser");
            @SuppressWarnings("unchecked")
            List<User> attUser = (List<User>)map.get("attUsers");
            modelAndView.addObject("attUsers", attUser);
            modelAndView.addObject("messageList", Messagelist);
            modelAndView.addObject("bUser", bUser);
            //重新查找未读私信数目
            Map<String, Object> alerts = userService.alerts(user.getId());
            session.setAttribute("alerts", alerts);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }




    //**********************************AJax请求***************************//

    /**
     * 微博关注用户
     * ajx中url:attention?operation=gz&attId=
     * aId:被关注用户id
     * uId:session中的用户id
     */
    @RequestMapping("/attention")
    public ModelAndView attentionServi(String operation, String attId, HttpSession session, HttpServletResponse response){
        modelAndView.clear();
        try {
            User user = (User)session.getAttribute("loginUser");
            PrintWriter pw = response.getWriter();
            if(user == null){
                pw.print("请登录");
                return null;
            }
            long bId = Long.parseLong(attId);
            User bUser = userService.findUserByID(bId);
            friendService.operationUser(operation, user, bUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param session
     * @param userBId	要私信的用户id
     * @return
     */
    @RequestMapping("/message")
    public ModelAndView message(HttpSession session,long userBId){
        modelAndView.clear();
        modelAndView.setViewName("friend/message");
        User user = (User)session.getAttribute("loginUser");
        try {
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            //查找用户有私信的记录
            Map<String, Object> map = friendService.findMessageNOReadById(user.getId(), userBId);
            @SuppressWarnings("unchecked")
            List<Message> messageList = (List<Message>) map.get("list");
            User bUser = (User) map.get("bUser");
            @SuppressWarnings("unchecked")
            List<User> attUser = (List<User>)map.get("attUsers");
            modelAndView.addObject("attUsers", attUser);
            modelAndView.addObject("messageList", messageList);
            modelAndView.addObject("bUser", bUser);

            //重新查找未读私信数目
            Map<String, Object> alerts = userService.alerts(user.getId());
            session.setAttribute("alerts", alerts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }





}
